<template>
    <!-- 事实外包方-新增 -->
    <div class="e-form">
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    label-width="150px"
                    :rules="rules"
                    ref="formData"
                >
                <BillTop title="事实外包方变更新增" @cancel="handleClose"></BillTop>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="统一社会信用代码"
                                prop="creditCode"
                            >
                                {{ formData.creditCode }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="外包方类别" prop="type">
                                <el-radio-group v-model="formData.type">
                                    <el-radio :label="0">分包商</el-radio>
                                    <el-radio :label="1">供应商</el-radio>
                                </el-radio-group>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.type != formData.type
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="外包方名称：" prop="outerName">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.outerName"
                                ></el-input>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.outerName !=
                                            formData.outerName
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="法人代表" prop="deputy">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.deputy"
                                ></el-input>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.deputy != formData.deputy
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="法人身份证号码："
                                prop="idCard"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.idCard"
                                    maxlength="18"
                                ></el-input>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.idCard != formData.idCard
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="法人身份证附件"
                                prop="deputyOssName"
                            >
                                <span
                                    @click="preview1()"
                                    style="
                                        disply: inline-block;
                                        width: 100%;
                                        color: blue;
                                        cursor: pointer;
                                        overflow: hidden;
                                    "
                                    >{{ formData.deputyOssName }}</span
                                >
                                <el-upload
                                    style="margin: 7px 5px 0px 0px"
                                    class="upload-demo"
                                    :action="uploadUrl"
                                    :data="{
                                        bucketName,
                                        relationId,
                                        orgCode
                                    }"
                                    :before-upload="beforeAvatarUpload"
                                    :accept="accept"
                                    :on-success="attachOnSuccess"
                                    :http-request="uploadBefore"
                                    :show-file-list="false"
                                    name="files"
                                >
                                    <el-button type="primary">上传</el-button>
                                </el-upload>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.deputyOssName !=
                                            formData.deputyOssName
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="注册资本(万元)："
                                prop="registeredCapital"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.registeredCapital"
                                    v-enterFloat2
                                ></el-input>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.registeredCapital !=
                                            formData.registeredCapital
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="营业执照"
                                prop="businessLicenseOssName"
                            >
                                <span
                                    @click="preview2()"
                                    style="
                                        disply: inline-block;
                                        width: 100%;
                                        color: blue;
                                        cursor: pointer;
                                        overflow: hidden;
                                    "
                                    >{{ formData.businessLicenseOssName }}</span
                                >
                                <el-upload
                                    style="margin: 7px 5px 0px 0px"
                                    class="upload-demo"
                                    :action="uploadUrl"
                                    :data="{
                                        bucketName,
                                        relationId,
                                        orgCode
                                    }"
                                    :before-upload="beforeAvatarUpload"
                                    :accept="accept"
                                    :on-success="attachOnSuccessBl"
                                    :http-request="uploadBeforeBl"
                                    :show-file-list="false"
                                    name="files"
                                >
                                    <el-button type="primary">上传</el-button>
                                </el-upload>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.businessLicenseOssName !=
                                            formData.businessLicenseOssName
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="库外单位">
                                <el-switch
                                    :width="60"
                                    v-model="formData.isOutOrg"
                                    class="main-el-switch"
                                    active-color="#13ce66"
                                    inactive-color="#D2D2D2"
                                    active-value="1"
                                    inactive-value="0"
                                    active-text="是"
                                    inactive-text="否"
                                      disabled
                                >
                                </el-switch>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.isOutOrg !=
                                            formData.isOutOrg
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="录入机构">{{
                                formData.orgName
                            }}</el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="注册地址" prop="address">
                                <SelectAddr
                                    v-model="formData.address"
                                    lazy
                                    showCountry
                                    style="width: 100%"
                                ></SelectAddr>
                                <img
                                    v-if="
                                        isLoad &&
                                        oldEditData.address != formData.address
                                    "
                                    class="img-style"
                                    src="@/assets/biangeng.png"
                                    alt=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                {{ statusLable(formData.state) }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
                >保存</el-button
            >
            <el-button @click="cancel()">取消</el-button>
        </div>
    </div>
</template>

<script>
import SelectAddr from '@/components/common/addrComp'
// 事实外包方
import correspondentUnit from '@/api/OutsourcingartyAdmin/correspondentUnit/correspondentUnit.js'
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import ossRequest from '@/api/oss/oss.js'
// import { showSuccessPop } from '@/utils/common'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import { creditCodeVerification, isIdcard } from '@/utils/rules'
export default {
    props: {
        bucketName: {
            type: String,
            default: '',
            require: true
        }
    },
    data () {
        return {
            //表单数据
            formData: {
                address: '', //	注册地址
                businessLicenseOss: '', //	营业执照附件主键
                businessLicenseOssName: '', //营业执照
                creditCode: '', //统一信用代码
                deputy: '', //法人
                deputyOss: '', //法人附加主键
                deputyOssName: '', //法人身份附件名字
                id: '', //主键
                idCard: '', //法人身份证
                isOutOrg: '', //是否是库外单位（0 不是 1是)
                orgId: '', //机构id
                orgName: '', //机构名称
                outerName: '', //外包方名称
                registeredCapital: 0, //注册资本
                state: 0, //	单据状态
                type: 0, //外包方类型（0 分包商 1 供应商）
                dialogImageUrl: '', //法人附加主键路径
                businessLicenseOssImage: '', //营业执照附件路径
                originalBillId: '' //原单id
            },
            businessList: [],
            unitList: [],
            oldEditData: {}, //原单数据，保证不变
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            //上传的地址
            uploadUrl: '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            relationId: '',
            billid: '', //原单id
            isLoad: false, //判断接口值回来没有
            // 验证
            rules: {
                // 统一社会信用代码
                creditCode: [
                    {
                        required: true,
                        validator: creditCodeVerification,
                        trigger: 'blur'
                    }
                ],
                //外包方类型
                type: [
                    {
                        required: true,
                        message: '请选择外包方类型',
                        trigger: 'blur'
                    }
                ],
                //外包方名称
                outerName: [
                    {
                        required: true,
                        message: '请输入外包方名称',
                        trigger: 'blur'
                    }
                ],
                //法人代表
                deputy: [
                    {
                        required: true,
                        message: '请输入法人代表',
                        trigger: 'blur'
                    }
                ],
                //法人身份证号码
                idCard: [
                    {
                        required: true,
                        validator: isIdcard,
                        trigger: 'blur'
                    }
                ],
                //法人身份证附件
                deputyOssName: [
                    {
                        required: true,
                        message: '请上传法人身份证附件',
                        trigger: 'change'
                    }
                ],
                //注册资本
                registeredCapital: [
                    {
                        required: true,
                        message: '请输入注册资本',
                        trigger: 'blur'
                    }
                ],
                //营业执照
                businessLicenseOssName: [
                    {
                        required: true,
                        message: '请上传营业执照',
                        trigger: 'change'
                    }
                ],
                //注册地址
                address: [
                    {
                        required: true,
                        message: '请选择注册地址',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    components: {
        SelectAddr
    },
    created () {
        this.billid = this.$route.query.billid
        this.getBusinesseData()
        this.getBasicData() //获取基础数据
    },
    computed: {
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    beforeDestroy () {},
    methods: {
        ...mapMutations(['setPopConfirm']),
        //获取业务类型数据
        getBusinesseData () {
            call.getCredential('往来单位业务类型').then(res => {
                this.businessList = res
            })
            call.getCredential('往来单位类型').then(res => {
                this.unitList = res
            })
        },
        //保存按钮
        save () {
            this.$refs.formData.validate(async valid => {
                if (valid) {
                    let data = JSON.parse(JSON.stringify(this.formData))
                    data.originalBillId = this.billid
                    let datas =
                        await correspondentUnit.correspondentUnitChangeAdd(
                            data
                        )
                    if (datas.code != 200) {
                        this.clientPop(
                            'info',
                            '保存成功！是否继续下一步操作？',
                            this.gocallback(datas),
                            null,
                            this.cancelCallBack(datas)
                        )
                    }
                }
            })
        },
        //获取基本信息数据
        async getBasicData () {
            let res = await correspondentUnit.getcorrespondentUnit({
                id: this.billid
            })
            this.isLoad = true
            //重置状态
            res.state = 0
            res.isOutOrg = res.isOutOrg + ''
            this.formData = res
            this.oldEditData = JSON.parse(JSON.stringify(res))
        },
        // 保存成功继续回调
        gocallback (billid) {
            return () => {
                this.$router.push({
                    path: '/factualOutsourcerChangeEdit',
                    query: { billid }
                })
            }
        },
        // 保存成功，取消回调
        cancelCallBack (billid) {
            return () => {
                this.$router.push({
                    path: '/FactualOutsourcer',
                    query: { billid }
                })
            }
        },
        //取消按钮
        cancel () {
            this.$router.push('/FactualOutsourcer')
        },
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取上传成功的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    this.formData.deputyOssName = res[0].objectName
                    this.formData.deputyOss = res[0].relationId
                    this.formData.deputyOssImage = res[0].objectPath
                })
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccess()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //营业执照上传成功
        attachOnSuccessBl () {
            this.getObjectByRelationIdBl()
        },
        //获取上传成功的对象
        getObjectByRelationIdBl () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    // 等后端确定id和名字。再赋值
                    this.formData.businessLicenseOssName = res[0].objectName
                    this.formData.businessLicenseOss = res[0].relationId
                    this.formData.businessLicenseOssImage = res[0].objectPath
                })
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBeforeBl (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccessBl()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //预览法人附件
        preview1 () {
            if (this.formData.deputyOssImage) {
                window.open(this.formData.deputyOssImage)
            }
        },
        //营业执照预览附件
        preview2 () {
            if (this.formData.businessLicenseOssImage) {
                window.open(this.formData.businessLicenseOssImage)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
// 变字
.img-style {
    width: 25px;
    height: 25px;
    margin: 0px 0px 4px 5px;
}
.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
// 境外单位
::v-deep .clearPadding .vxe-cell {
    padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
    padding-left: 0px;
}
::v-deep {
    .main-el-switch {
        position: relative;
        .el-switch__core {
            height: 24px;
            border-radius: 12px;
            &:after {
                left: 4px;
                top: 3px;
            }
        }
        &.el-switch {
            &.is-checked {
                .el-switch__core {
                    &:after {
                        margin-left: -20px;
                        left: 100%;
                    }
                }
            }
        }
        &.is-checked {
            .el-switch__label--left {
                opacity: 0;
            }
            .el-switch__label--right {
                opacity: 1;
            }
        }
        .el-switch__label {
            position: absolute;
            top: 0;
        }
        .el-switch__label--left {
            right: 0;
            color: #999;
            z-index: 1;
            margin-right: 8px;
        }
        .el-switch__label--right {
            left: 0;
            color: #fff;
            opacity: 0;
            margin-left: 8px;
        }
    }
}
</style>
